<?php

namespace app\api\controller;

use app\common\lib\Sensitive;
use app\common\model\MemberPointsLog;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\facade\View;
use think\facade\Db;
use think\response\Json;

/**
 * 聊天
 *
 * api-Chat
 *
 * @Apidoc\Title("聊天")
 * @Apidoc\Group("api")
 */
class Chat extends Auth
{
    /**
     * list
     * @Apidoc\Title("聊天列表")
     */
    public function list()
    {
        $data = \app\common\model\Chat::where('member_id', $this->request->uid)
            ->order('id', 'desc')->select();
        return success('', $data);
    }

    /**
     * update
     * @Apidoc\Title("更新聊天名称")
     * @return Json
     */
    public function update()
    {
        $data = $this->request->post(['id', 'name']);
        $member_id = \app\common\model\Chat::where('id', $data['id'])->value('member_id');
        if ($member_id != $this->request->uid) {
            return error('非法请求！');
        }
        \app\common\model\Chat::update($data);
        return success();
    }

    /**
     * delete
     * @Apidoc\Title("删除聊天")
     * @return Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete()
    {
        $id = input('id');
        $member_id = \app\common\model\Chat::where('id', $id)->value('member_id');
        if ($member_id != $this->request->uid) {
            return error('非法请求！');
        }
        $cat = \app\common\model\Chat::with('chatMessages')->find($id);
        $cat->together(['chatMessages'])->delete();
        return success();
    }


    /**
     * deleteAll
     * @Apidoc\Title("清空聊天记录")
     */
    public function deleteAll(): Json
    {
        $ids = \app\common\model\Chat::where('member_Id', $this->request->uid)->column('id');
        foreach ($ids as $id){
            $cat = \app\common\model\Chat::with('chatMessages')->find($id);;
            $cat->together(['chatMessages'])->delete();
        }
        return success();
    }


    /**
     * add
     * @Apidoc\Title("新增聊天")
     */
    public function add()
    {
        $data = request()->post(['name', 'id']);
        $initial_prompt_words = '';
        if($data['id']){
            $prompt=\app\common\model\ChatPrompt::find($data['id']);
            $prompt->number_of_uses=Db::raw('number_of_uses+1');
            $prompt->save();
            $initial_prompt_words=$prompt['chat_prompt'];
        }
        $create['chat_prompt_id'] = $data['id'];
        $create['member_id'] = $this->request->uid;
        $create['name'] = $data['name'];
        $create['initial_prompt_words'] = $initial_prompt_words;
        \app\common\model\Chat::create($create);
        $data = \app\common\model\Chat::where('member_id', $this->request->uid)
            ->order('id', 'desc')->select();
        return success('', $data);

    }

    /**
     * getAccess
     * @Apidoc\Title("能否生成")
     */
    public function getAccess()
    {
        $data = input();
        /******************言论审查开始***********************************/
        //数据检验开始，这里审查用户的言论是否符合国家法律规定，这里一定要加上++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $TextModeration=new \app\api\service\TextModerationService();
        if (!$TextModeration->check(json_encode($this->request->param(),JSON_UNESCAPED_UNICODE))) {
            return error($TextModeration->msg);
        }
        /*****************言论审查结束了**********************************/
        $key_word = $data['msg'];
        if (!$key_word) {
            return error('内容不能为空');
        }
        $res = Sensitive::has($key_word);
        if ($res) {
            //return error('不能包含敏感词：' . Sensitive::get($key_word));
            return error('不能包含敏感词');
        }
        // 验证积分
        $member = \app\common\model\Member::find($this->request->uid);
        $number_of_free_chats = $member['number_of_free_chats'];
        $chat_expiration_time = $member['chat_end_time'];
        if ($chat_expiration_time < time()) {
            if ($number_of_free_chats <= 0) {
                return error('体验次数不足, 请充值会员！', ['action' => 'recharge']);
            } else {
                $member->number_of_free_chats = $member->number_of_free_chats - 1;
                $member->save();
            }
        }

        $random_key = uniqid();
        cache($random_key, $key_word, ['expire' => 100]);
        return success('', ['key' => $random_key]);
    }


    /**
     * getData
     * @Apidoc\Title("获取聊天消息")
     */
    public function getData(): Json
    {
        $id = input('id');
        $data = \app\common\model\ChatMessages::where('chat_id', $id)->order('id', 'asc')->field('content,response')->select();
        return success('', $data);
    }

}
